<template>
  <div id="editorContainer"></div>
</template>

<script setup lang="ts">
import * as monaco from 'monaco-editor';	// 全部导入
import { onUnmounted, watch } from 'vue';
import { ref, onMounted } from 'vue';


const props = defineProps<{ 'modelValue': string, 'language': string }>()
const emits = defineEmits<{
  (e: 'update:modelValue', val: string): void,
}>()

let editor: any = null;
const mValue = ref('');

onMounted(() => {
  editor = monaco.editor.create(document.getElementById('editorContainer') as HTMLElement, {
    value: mValue.value || '',
    language: props.language || 'javascript',
    minimap: {
      enabled: false,
    },
    colorDecorators: true,		//颜色装饰器
    // readOnly: true,			//是否开启已读功能
    theme: "vs-dark",			//主题
    automaticLayout: true,
    fontSize: 14,
    lineNumbers: 'on',
  }) as any;

  // 监听编辑器内容变化
  editor.onDidChangeModelContent(() => {
    // 触发父组件的 change 事件，通知编辑器内容变化
    // emits('update:modelValue',editor.getValue())
    
  });
  // 失去焦点
  editor.onDidBlurEditorWidget(() => {
    emits('update:modelValue', editor.getValue())
  });
});

onUnmounted(()=>{
  editor&&editor.dispose();
  editor = null
})
watch(() => props.modelValue, (val) => {
  mValue.value = val;
  if (editor&&val) {
    editor.setValue(val)
  }
},{
  immediate: true,
  deep: true,
})
</script>
<style scope lang="scss">
#editorContainer {
  height: 100%;
  width: 100%;

  min-height: 300px;
}
</style>
